package hu.veilingsite.gui;

import java.util.ArrayList;
import java.util.Date;

import hu.veilingsite.client.Service;
import hu.veilingsite.client.ServiceAsync;
import hu.veilingsite.shared.Auction;
import hu.veilingsite.shared.Category;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ShowAuctions {
	private TextBox TB_auction_name;
	private ListBox LB_auction_cat;
	private VerticalPanel auctionPanel;
	private Button BTN_search;
	private ArrayList<Category> categories;
	private ArrayList<Auction> auctions;
	private final ServiceAsync myService = GWT.create(Service.class);

	public ShowAuctions() {
		auctionPanel = new VerticalPanel();
		categories = new ArrayList<Category>();
		// header
		RootPanel.get("main").add(new HTML("<h1>Alle veilingen</h1>"));
		AsyncCallback<ArrayList<Category>> getCategoriesCallback = new AsyncCallback<ArrayList<Category>>() {

			@Override
			public void onFailure(Throwable caught) {
				auctionPanel.clear();
				auctionPanel.add(new HTML("Er is een fout opgetreden in het systeem."));
			}

			@Override
			public void onSuccess(ArrayList<Category> result) {
				categories = result;
				// Filter menu
				FlexTable filterTable = new FlexTable();
				filterTable.addStyleName("filterTable");
				filterTable.setWidget(0, 0, new HTML("Filter op:"));
				filterTable.setWidget(1, 0, new Label("naam: "));
				filterTable.setWidget(1, 1, TB_auction_name = new TextBox());
				filterTable.setWidget(1, 2, new Label("category: "));
				// categories
				LB_auction_cat = new ListBox();
				LB_auction_cat.addItem("alle", "-1");
				for (int i = 0; i < categories.size(); i++) {
					Category cat = categories.get(i);
					LB_auction_cat.addItem(cat.getTitle(), "" + cat.getId());
				}
				filterTable.setWidget(1, 3, LB_auction_cat);
				// search button
				BTN_search = new Button("Zoek");
				BTN_search.addClickHandler(new ClickHandler() {
					public void onClick(ClickEvent e) {
						auctionPanel.clear();
						getAuctions();
					}
				});
				filterTable.setWidget(1, 4, BTN_search);
				// add filter
				RootPanel.get("main").add(filterTable);
				// print auctions
				getAuctions();
			}
		};
		myService.getCategories(getCategoriesCallback);
	}

	public Panel createPage() {
		return null;
	}

	public void getAuctions() {
		AsyncCallback<ArrayList<Auction>> getAllAuctions = new AsyncCallback<ArrayList<Auction>>() {

			@Override
			public void onFailure(Throwable caught) {
				auctionPanel.clear();
				auctionPanel.add(new HTML("Er is een fout opgetreden in het systeem."));
			}

			@Override
			public void onSuccess(final ArrayList<Auction> result) {
				if (result.size() > 0) {
					auctions = result;
					int searchCategoryId = Integer.parseInt(LB_auction_cat.getValue(LB_auction_cat.getSelectedIndex()));
					int catId = 0;
					boolean noVeilingenFound = true;

					for (int i = 0; i < categories.size(); i++) {
						catId = categories.get(i).getId();
						if (searchCategoryId != -1 && searchCategoryId == catId) {
							if (printAuction(catId, categories.get(i).getTitle())) {
								noVeilingenFound = false;
							}
						} else if (searchCategoryId == -1) {
							if (printAuction(catId, categories.get(i).getTitle())) {
								noVeilingenFound = false;
							}
						}
					}
					if(noVeilingenFound){
						auctionPanel.clear();
						auctionPanel.add(new HTML("Er zijn geen veilingen die voldoen aan uw zoekcriteria.<br/>Pas uw zoekcriteria aan."));
					}
				} else {
					auctionPanel.clear();
					auctionPanel.add(new HTML(
							"Er zijn geen veilingen gevonden!"));
				}
			}

			public boolean printAuction(int catId, String catName) {
				// create panel
				FlexTable categoriePanel = new FlexTable();
				categoriePanel.addStyleName("categorieTable");
				categoriePanel.setCellSpacing(0);
				// veilingen
				boolean veilingFound = false;
				boolean noVeilingenFound = true;
				// add Auction Data to categoriePanel
				categoriePanel.setWidget(0, 0, new HTML("<h2>" + catName + "</h2>"));
				for (int i = 0; i < auctions.size(); i++) {
					Auction auction = auctions.get(i);
					if (!TB_auction_name.getText().isEmpty() && auction.getTitle().toLowerCase().matches(".*("+ TB_auction_name.getText().toLowerCase() + ").*")) {
						veilingFound = true;
					} else if (TB_auction_name.getText().isEmpty()){
						veilingFound = true;
					} else {
						veilingFound = false;
					}
					if (auction.getCategory_id() == catId && veilingFound) {
						noVeilingenFound = false;
						categoriePanel.setWidget(i + 2, 0, new HTML(auction.getTitle()));
						categoriePanel.setWidget(i + 2, 1, new HTML("" + auction.getStartprice()));
						categoriePanel.setWidget(i + 2, 2, new HTML(auction.getEndDate().toString()));
						categoriePanel.setWidget(i + 2, 3, new HTML(tijdover(auction.getEndDate())));

						final int aucId = auction.getId();
						ClickHandler bekijkHandler = new ClickHandler() {
							@Override
							public void onClick(ClickEvent event) {
								RootPanel.get("main").clear();
								RootPanel.get("main").add(
										new ViewAuction(aucId).createPage());
							}
						};
						categoriePanel.setWidget(i + 2, 4, new Button("Bekijk",bekijkHandler));
					}
				}
				if (noVeilingenFound) {
					categoriePanel.clear();
					auctionPanel.add(categoriePanel);
					return false;
				} else {
					// create header categoriePanel
					categoriePanel.setWidget(1, 0, new HTML("<b>Titel</b>"));
					categoriePanel.setWidget(1, 1, new HTML("<b>Gestart met</b>"));
					categoriePanel.setWidget(1, 2, new HTML("<b>Loopt tot</b>"));
					categoriePanel.setWidget(1, 3, new HTML("<b>Tijd over</b>"));
					auctionPanel.add(categoriePanel);
					return true;
				}
				
			}
		};
		myService.getAllAuctions(getAllAuctions);
		RootPanel.get("main").add(auctionPanel);
	}

	public String tijdover(Date einddatum) {
		Date until = new Date(einddatum.getTime());
		Date now = new Date();
		String tijdover = "";
		long timeleft = until.getTime() - now.getTime();
		if (timeleft > 0) {
			// Easy as that ;D
			long days = (long) Math.ceil(timeleft / (1000 * 60 * 60 * 24));
			timeleft = timeleft - (days * (1000 * 60 * 60 * 24));
			if (days > 0)
				tijdover += days + " dagen ";
			long hours = (long) Math.ceil(timeleft / (1000 * 60 * 60));
			timeleft = timeleft - (hours * (1000 * 60 * 60));
			if (hours > 0)
				tijdover += hours + " uur ";
			long min = (long) Math.ceil(timeleft / (1000 * 60));
			timeleft = timeleft - (min * (1000 * 60));
			if (min > 0)
				tijdover += min + " min ";
			long sec = (long) Math.ceil(timeleft / (1000));
			timeleft = timeleft - (sec * (1000));
			tijdover += sec + " sec.";
		} else {
			tijdover = "Veiling gesloten.";
		}
		return tijdover;
	}
}